package com.yy.wga.common.web.config;

import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring.http.converter.FastJsonHttpMessageConverter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

/**
 * @author 侯建军
 * @日 期: 2018/11/20 16:39:19
 * @描 述:  web配置
 */
@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {

    public HttpMessageConverter<String> stringConverter() {
        return new StringHttpMessageConverter(
                StandardCharsets.UTF_8);
    }

    public HttpMessageConverter<?> fastConverter() {
        //1、定义一个convert转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //2、添加fastjson的配置信息
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setCharset(StandardCharsets.UTF_8);
        fastJsonConfig.setWriterFeatures(JSONWriter.Feature.PrettyFormat,
                //字符串null返回空字符串
                JSONWriter.Feature.WriteNullStringAsEmpty,
                //数值类型为0
                JSONWriter.Feature.WriteNullNumberAsZero,
                //空字段保留
                JSONWriter.Feature.WriteNullListAsEmpty,
                JSONWriter.Feature.WriteMapNullValue);
        //2-1 处理中文乱码问题
        java.util.List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON);
        // 用于spring boot actuator使用
        fastMediaTypes.add(MediaType.valueOf("application/vnd.spring-boot.actuator.v3+json"));
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        //3、在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);
        return fastConverter;
    }

    @Override
    public void extendMessageConverters(java.util.List<HttpMessageConverter<?>> converters) {
        converters.clear();
        converters.add(stringConverter());
        converters.add(fastConverter());
    }
}
